<template>
  <div class="address-container">
    
    <!-- 返回按钮 -->
    <view class="back-btn" @click="goBack">
      <text class="cuIcon-back"></text> 返回
    </view>
    
    <!-- 标题 -->
    <div class="header">
      <div class="header-content">
        <h2>我的地址列表</h2>
        <p>管理您的收货地址信息</p>
      </div>
    </div>
    
    <!-- 地址列表 -->
    <div class="address-list">
      <!-- 动态渲染地址卡片 -->
      <div v-for="address in addressList" :key="address.addressId" class="address-card" @click="selectAddress(address.addressId)">
        <div class="radio-container">
          <div class="radio" :class="{ 'selected': selectedAddress === address.addressId }">
            <div v-if="selectedAddress === address.addressId" class="radio-inner"></div>
          </div>
        </div>
        <div :class="['avatar', getAvatarColor(address.addressId)]">
          <i class="icon-location"></i>
        </div>
        <div class="address-info">
          <div class="name">{{ address.client }}</div>
          <div class="phone">{{ address.clientPhone }}</div>
          <div class="address">{{ address.address || '暂无详细地址' }}</div>
          <!-- <div class="coordinate">坐标：{{ address.longitude }}, {{ address.latitude }}</div> -->
        </div>
        <!-- 添加修改和删除按钮 -->
        <div class="action-buttons">
          <button class="edit-btn" @click.stop="showEditModal(address)">
            <i class="icon-edit"></i>修改
          </button>
          <button class="delete-btn" @click.stop="showDeleteConfirm(address.addressId)">
            <i class="icon-delete"></i>删除
          </button>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="addressList.length === 0" class="empty-state">
        <div class="empty-icon">📍</div>
        <h3>暂无地址信息</h3>
        <p>点击下方按钮添加您的第一个地址</p>
      </div>
    </div>
    
    <!-- 添加按钮 -->
    <div class="add-button" @click="addNewAddress">
      <router-link to="/pages/address/InitAddress" class="add-button"></router-link>
      <button>
        <i class="icon-add"></i>
        添加新地址
      </button>
    </div>

    <!-- 修改地址弹框 -->
    <div v-if="showEditDialog" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>修改地址信息</h3>
          <button class="close-btn" @click="closeEditModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>地址：</label>
            <input v-model="editForm.address" type="text" placeholder="请输入详细地址">
          </div>
          <div class="form-group">
            <label>姓名：</label>
            <input v-model="editForm.client" type="text" placeholder="请输入姓名">
          </div>
          <div class="form-group">
            <label>电话：</label>
            <input v-model="editForm.clientPhone" type="text" placeholder="请输入电话号码">
          </div>
          <div class="form-group">
            <label>性别：</label>
            <select v-model="editForm.clientSex">
              <option value="1">男</option>
              <option value="0">女</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeEditModal">取消</button>
          <button class="confirm-btn" @click="confirmEdit">确定</button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹框 -->
    <div v-if="showDeleteDialog" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content delete-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-body">
          <div class="warning-icon">⚠️</div>
          <p class="warning-text">此操作不可改变，确定要删除这个地址吗？</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeDeleteModal">取消</button>
          <button class="delete-confirm-btn" @click="confirmDelete">确定删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { post, get } from '@/utils/request.js'; 

// 后端接口地址
const ADDRESS_LIST_API = `/adress/useradressse`;
const ADDRESS_UPDATE_API = `/adress/useradressup`;
const ADDRESS_DELETE_API = `/adress/useradressde`;

export default {
  setup() {
    const addressId=ref(null);  // 确保在 data 中定义
    const selectedAddress = ref(null); 
    const addressList = ref([]); 
    const showEditDialog = ref(false);
    const showDeleteDialog = ref(false);
    const currentAddressId = ref(null);
    const editForm = ref({
      address: '',
      client: '',
      clientPhone: '',
      clientSex: 1
    });

    // 获取地址列表
    const fetchAddressList = async () => {
      try {
        //获取用户id
        const user = JSON.parse(uni.getStorageSync('user'));
        const userId = user.userId ;
        //根据用户id获取用户地址
        const response = await get(`${ADDRESS_LIST_API}?userId=${userId}`);
        if (response.data.code === 200) {
          addressList.value = response.data.msg;
          console.log(addressList)
          // 查找isDefault为1的地址
          let defaultAddress = addressList.value.find(addr => addr.isDefault === 1);
          // 如果没有isDefault为1的，取第一个
          if (!defaultAddress && addressList.value.length > 0) {
            defaultAddress = addressList.value[0];
          }
          if (defaultAddress) {
            selectedAddress.value = defaultAddress.addressId;
            // 存储默认地址和经纬度
            uni.setStorageSync('selectedAddress', defaultAddress.address);
            uni.setStorageSync('latitude', defaultAddress.latitude);
            uni.setStorageSync('longitude', defaultAddress.longitude);
          }
        } else {
          console.error('获取地址列表失败:', response.data.msg);
        }
      } catch (error) {
        console.error('获取地址列表失败', error);
      }
    };

    const selectAddress = (id) => {
      selectedAddress.value = id;
      // 找到选中的地址对象
      const selected = addressList.value.find(addr => addr.addressId === id);
      if (selected) {
        // 将选中的地址存入本地存储
        uni.setStorageSync('selectedAddress', selected.address);
        // 将地址经纬度存入本地存储
        uni.setStorageSync('latitude', selected.latitude);
        uni.setStorageSync('longitude', selected.longitude);
        // 返回上一页
        uni.navigateBack();
      }
    };

    const addNewAddress = () => {
      console.log('添加新地址');
      // 这里可以添加跳转到添加地址页面的逻辑
      setTimeout(() => {
  uni.navigateTo({ 
    url: '/pages/address/InitAddress'  // 非Tab页跳转
  });
}, 1000);
   
    };

    // 显示修改弹框
    const showEditModal = (address) => {
      // 跳转到编辑页面，传递地址数据
      uni.navigateTo({
        url: `/pages/address/InitAddress?mode=edit&addressId=${address.addressId}&address=${encodeURIComponent(address.address || '')}&client=${encodeURIComponent(address.client || '')}&clientPhone=${encodeURIComponent(address.clientPhone || '')}&clientSex=${address.clientSex || 1}`
      });
    };

    // 关闭修改弹框
    const closeEditModal = () => {
      showEditDialog.value = false;
      editForm.value = {
        address: '',
        client: '',
        clientPhone: '',
        clientSex: 1
      };
      currentAddressId.value = null;
    };

    // 确认修改
    const confirmEdit = async () => {
      try {
        // 获取表单数据
        const { address, client, clientPhone, clientSex } = editForm.value;
        
        // 表单验证
        if (!client.trim()) {
          alert('请输入姓名');
          return;
        }
        
        if (!clientPhone.trim()) {
          alert('请输入电话号码');
          return;
        }
        
        // 构建请求URL，对参数进行编码
        const params = new URLSearchParams({
          addressId: currentAddressId.value,
          address: address || '',
          client: client.trim(),
          clientPhone: clientPhone.trim(),
          clientSex: clientSex || 1
        });
        
        const response = await get(`${ADDRESS_UPDATE_API}?${params.toString()}`);
        
        if (response.data.code === 200) {
          console.log('地址修改成功');
          alert('地址修改成功！');
          closeEditModal();
          // 刷新地址列表
          await fetchAddressList(); 
        } else {
          console.error('地址修改失败:', response.data.msg);
          alert(`地址修改失败: ${response.data.msg}`);
        }
      } catch (error) {
        console.error('地址修改失败', error);
        alert('地址修改失败，请稍后重试');
      }
    };

    // 显示删除确认弹框
    const showDeleteConfirm = (addressId) => {
      currentAddressId.value = addressId;
      showDeleteDialog.value = true;
    };

    // 关闭删除弹框
    const closeDeleteModal = () => {
      showDeleteDialog.value = false;
      currentAddressId.value = null;
    };

    // 确认删除
    const confirmDelete = async () => {
      try {
        const response = await get(`${ADDRESS_DELETE_API}?addressId=${currentAddressId.value}`);
        
        if (response.data.code === 200) {
          console.log('地址删除成功');
          alert('地址删除成功！');
          closeDeleteModal();
          // 刷新地址列表
          await fetchAddressList(); 
        } else {
          console.error('地址删除失败:', response.data.msg);
          alert(`地址删除失败: ${response.data.msg}`);
        }
      } catch (error) {
        console.error('地址删除失败', error);
        alert('地址删除失败，请稍后重试');
      }
    };

    // 根据地址ID生成不同的头像颜色
    const getAvatarColor = (addressId) => {
      const colors = ['blue', 'green', 'orange', 'purple', 'red', 'teal'];
      return colors[addressId % colors.length];
    };

    const goBack = () => {
      uni.navigateBack();
    };

    onMounted(() => {
      fetchAddressList();
    });

    return {
      selectedAddress,
      addressList,
      showEditDialog,
      showDeleteDialog,
      editForm,
      selectAddress,
      addNewAddress,
      showEditModal,
      closeEditModal,
      confirmEdit,
      showDeleteConfirm,
      closeDeleteModal,
      confirmDelete,
      getAvatarColor,
      goBack
    };
  }
};
</script>

<style scoped>
.address-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 40px;
  padding: 30px 0;
}

.header-content {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.header h2 {
  color: #333;
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header p {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.address-card {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  position: relative;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.address-card:hover {
  transform: translateY(-4px) scale(1.02);
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.15);
}

.radio-container {
  margin-right: 20px;
}

.radio {
  width: 24px;
  height: 24px;
  border: 3px solid #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.radio.selected {
  border-color: #667eea;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.2);
}

.radio-inner {
  width: 10px;
  height: 10px;
  background-color: white;
  border-radius: 50%;
  animation: radioPop 0.3s ease;
}

@keyframes radioPop {
  0% { transform: scale(0); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  color: white;
  font-size: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s ease;
}

.avatar:hover {
  transform: scale(1.1);
}

.avatar.blue { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.avatar.green { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.avatar.orange { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.avatar.purple { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.avatar.red { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.avatar.teal { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); }

.address-info {
  flex: 1;
  margin-right: 20px;
}

.name {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin-bottom: 8px;
}

.phone {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.phone::before {
  content: "📞";
  margin-right: 8px;
}

.address {
  font-size: 15px;
  color: #888;
  margin-bottom: 8px;
  line-height: 1.5;
  display: flex;
  align-items: center;
}

.address::before {
  content: "📍";
  margin-right: 8px;
}

.coordinate {
  font-size: 13px;
  color: #999;
  font-family: 'Courier New', monospace;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 6px;
  display: inline-block;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons button {
  padding: 10px 18px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.edit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.edit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.delete-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
}

.delete-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  backdrop-filter: blur(10px);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.6;
}

.empty-state h3 {
  color: #333;
  font-size: 20px;
  margin-bottom: 10px;
}

.empty-state p {
  color: #666;
  font-size: 16px;
}

.add-button {
  margin-top: 40px;
  text-align: center;
}

.add-button button {
  padding: 18px 36px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 30px;
  font-size: 18px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4);
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0 auto;
}

.add-button button:hover {
  transform: translateY(-3px) scale(1.05);
  box-shadow: 0 12px 40px rgba(102, 126, 234, 0.6);
}

/* 弹框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease;
}

@keyframes modalSlideIn {
  0% { transform: translateY(-50px); opacity: 0; }
  100% { transform: translateY(0); opacity: 1; }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #666;
}

.modal-body {
  padding: 25px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 600;
  font-size: 14px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group input[readonly] {
  background-color: #f8f9fa;
  color: #666;
  cursor: not-allowed;
  border-color: #e9ecef;
}

.form-group input[readonly]:focus {
  border-color: #e9ecef;
  box-shadow: none;
}

.modal-footer {
  display: flex;
  gap: 12px;
  padding: 20px 25px;
  border-top: 1px solid #eee;
  justify-content: flex-end;
}

.cancel-btn {
  padding: 10px 20px;
  border: 2px solid #e0e0e0;
  background: white;
  color: #666;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  border-color: #ccc;
  background: #f8f9fa;
}

.confirm-btn {
  padding: 10px 20px;
  border: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 删除确认弹框特殊样式 */
.delete-modal .modal-body {
  text-align: center;
  padding: 30px 25px;
}

.warning-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.warning-text {
  color: #666;
  font-size: 16px;
  line-height: 1.5;
  margin: 0;
}

.delete-confirm-btn {
  padding: 10px 20px;
  border: none;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.delete-confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

.icon-location::before {
  content: "📍";
}

.icon-edit::before {
  content: "✏️";
}

.icon-delete::before {
  content: "🗑️";
}

.icon-add::before {
  content: "➕";
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-container {
    padding: 15px;
  }
  
  .address-card {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: center;
  }
  
  .header h2 {
    font-size: 24px;
  }
  
  .name {
    font-size: 18px;
  }
  
  .modal-content {
    width: 95%;
    margin: 20px;
  }
}

.back-btn {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #333;
  padding: 12px 0 12px 8px;
  cursor: pointer;
  width: fit-content;
}

.back-btn .cuIcon-back {
  font-size: 22px;
  margin-right: 6px;
}

.back-btn:hover {
  color: #667eea;
}
</style>